<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<canvas id="test"></canvas>
		<div id="main_color" style="background:darkgray;width: 30%;">
			<text id="main_text">主颜色</text>
		</div>
		<script>
			var canvas = document.querySelector("#test");
			var color_div = document.querySelector("#main_color");
			var color_text = document.querySelector("#main_text");
			var cxt = canvas.getContext("2d");

			window.onload = function() {
				var img = new Image();
				img.src = "user.jpg";
				// 加载完成图片之后才能够执行canvas的操作
				img.onload = function() {
					// displayImage(img)
					displayImageColor(img)
				}
			}

			function displayImage(img) {
				canvas.width = 293;
				canvas.height = 220;
				cxt.drawImage(img, 0, 0, 293, 220);
			}

			function displayImageColor(img) {
				mainColor = getImageColor(img)
				console.log(mainColor)
				color_div.style.background = "#" + mainColor
				color_text.textContent = "#" + mainColor
			}

			function getImageColor(img) {
				canvas.width = img.width
				canvas.height = img.height
				let context = canvas.getContext('2d')
				console.log(img.width, img.height)
				context.drawImage(img, 0, 0)

				// 获取像素数据
				let imageData = context.getImageData(0, 0, img.width, img.height).data
				console.log("imageData", imageData);
				let r = 0,
					g = 0,
					b = 0
				// 取所有像素的平均值
				for (let row = 0; row < img.height; row++) {
					for (let col = 0; col < img.width; col++) {
						r += imageData[(img.width * row + col) * 4]
						g += imageData[(img.width * row + col) * 4 + 1]
						b += imageData[(img.width * row + col) * 4 + 2]
					}
				}
				// 求取平均值
				r /= img.width * img.height
				g /= img.width * img.height
				b /= img.width * img.height

				// 将最终的值取整
				r = Math.round(r)
				g = Math.round(g)
				b = Math.round(b)

				//rgb转16进制 位运算
				const color = ((r << 16) | (g << 8) | b).toString(16)
				return color
			}
		</script>
	</body>
</html>
